<template>
	<view class="resume-container">
		<view class="resume-form">
			<view class="resume-form-item avatar">
				<view class="form-item-label">
					<text class="label">头像</text>
					<text class="label-tip">请使用真实照片</text>
				</view>
				<button class="avatar-wrap" open-type="chooseAvatar" @chooseavatar="uploadAvatar">
					<image v-if="form.userHead" class="avatar-box" :src="api_host + form.userHead" mode=""></image>
					<image class="default-avatar" v-else src="https://hxs.dsjhs.com:553/prod-api/profile/upload.png"
						mode=""></image>
				</button>
			</view>
			<view class="resume-form-item">
				<text class="label">姓名</text>
				<input class="input-text" v-model="form.userName" type="text" placeholder="请填写您的姓名">
			</view>
			<view class="resume-form-item">
				<text class="label">性别</text>
				<picker :value="genderIndex" :range="genderList" @change="handleChangeGender">
					<input class="input-text select" v-model="genderList[genderIndex]" disabled type="text" readonly
						placeholder="请选择您的性别">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">出生年月日</text>
				<picker mode="date" :value="form.birthTime" fields="day" :start="startDate" :end="endDate"
					@change="handleChangeBirthDay">
					<input class="input-text select" v-model="form.birthTime" disabled type="text"
						placeholder="请选择您的出生年月">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">身份证号</text>
				<input class="input-text" v-model="form.identityCard" type="text" placeholder="请填写您的身份证号">
			</view>
			<view class="resume-form-item">
				<text class="label">参加工作时间</text>
				<picker mode="date" :value="form.workTime" fields="month" :start="startDate" :end="endDate"
					@change="handleChangeWorkDay">
					<input class="input-text select" v-model="form.workTime" disabled type="text"
						placeholder="请选择您的参加工作时间">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">手机号</text>
				<input class="input-text" v-model="form.userPhone" type="number" placeholder="请填写您的手机号码">
			</view>
			<view class="resume-form-item">
				<text class="label">邮箱</text>
				<input class="input-text" v-model="form.userEmail" type="text" placeholder="请填写您的电子邮箱">
			</view>
			<view class="resume-form-item">
				<text class="label">毕业院校</text>
				<input class="input-text" v-model="form.userSchool" type="text" placeholder="请填写您的毕业院校">
			</view>
			<view class="resume-form-item">
				<text class="label">学历</text>
				<picker :value="stationEduIndex" :range="dicList" @change="handleChangeStationEduIndex">
					<input class="input-text select" v-model="dicList[stationEduIndex]" disabled type="text" readonly
						placeholder="请选择您的学历">
				</picker>
				<!-- <input class="input-text" v-model="form.userEducation" type="text" placeholder="请填写您的学历"> -->
			</view>
			<view class="resume-form-item">
				<text class="label">专业</text>
				<input class="input-text" v-model="form.userMajor" type="text" placeholder="请填写您的专业">
			</view>
			<view class="resume-form-item">
				<text class="label">在校入学时间</text>
				<picker mode="date" :value="enrolStartDate" fields="month" :start="startDate" :end="endDate"
					@change="handleChangeEnrolStartDate">
					<input class="input-text select" v-model="enrolStartDate" disabled type="text"
						placeholder="请选择您的在校时间">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">在校毕业时间</text>
				<picker mode="date" :value="enrolEndDate" fields="month" :start="startDate" :end="endDate"
					@change="handleChangeEnrolEndDate">
					<input class="input-text select" v-model="enrolEndDate" disabled type="text"
						placeholder="请选择您的在校时间">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">薪资期望</text>
				<picker :value="salaryIndex" :range="salaryList" @change="handleChangeSalary">
					<input class="input-text select" v-model="form.hopeSalary" disabled type="text"
						placeholder="请选择您的薪资期望">
				</picker>
			</view>
			<view class="resume-form-item">
				<text class="label">上传附件</text>
				<view class="input-text select" id="uploadBox" @click="chooseFile" style="width: 70%;">
					<view class="file-box" v-if="fileList.length">
						<text class="ellipsis" style="margin-right: 8px;font-size: 28rpx;line-height: 24px;">{{ fileList[0].name }}</text>
						<u-icon name="trash" color="#2979ff" size="24" @click.stop="delFile"></u-icon>
					</view>
				</view>
			</view>
			<view class="resume-form-item introduct">
				<view class="experience-head">
					<text class="label">工作经历</text>
					<view class="add-btn" @click="handleAddWorkExperience('')"></view>
				</view>
				<view class="experience-list" v-if="form.userResumeDetailList && form.userResumeDetailList.length">
					<view class="experience-item" v-for="(item, index) in form.userResumeDetailList" :key="index"
						@tap="handleAddWorkExperience(index)">
						<text class="company-name">{{ item.companyName }}</text>
						<text class="job-name">{{ item.stationName }}</text>
						<text class="work-date">{{ item.entryTime }}~{{ item.resignTime }}</text>
						<rich-text class="work-desc" :nodes="item.jobDesc"></rich-text>
					</view>
				</view>
			</view>
			<view class="resume-form-item introduct">
				<text class="label">个人简介</text>
				<textarea class="textarea-text" v-model="form.userBlurb" :maxlength="maxLength" placeholder="请填写个人简介" />
				<text class="count">{{ form.userBlurb.length }}/ {{ maxLength }}</text>
			</view>
		</view>
		<view class="submit-btn" @tap="handleSubmit">
			<button>保存</button>
		</view>
	</view>
</template>

<script>
	import {
		addResume,
		getResume,
		dictionary,
		updateResume
	} from '@/common/api_employment.js'

	export default {
		data() {
			return {
				form: {
					userHead: '',
					userName: '',
					userSex: '',
					birthTime: '',
					identityCard: '',
					workTime: '',
					userPhone: '',
					userEmail: '',
					userSchool: '',
					userEducation: '',
					userMajor: '',
					enrolTime: '',
					hopeSalary: '',
					userBlurb: '',
					fileName: '',
					attachment: '',
					userResumeDetailList: []
				},
				enrolStartDate: '',
				enrolEndDate: '',
				genderIndex: -1,
				stationEduIndex: -1,
				salaryIndex: -1,
				genderList: ['男', '女'],
				salaryList: ['面议', '1000~2000', '2000~3000', '3000~4000', '4000~5000', '5000~6000', '6000~7000',
					'7000~8000', '8000~9000', '9000~10000', '10000以上'
				],
				maxLength: 1000,
				dicList: [],
				fileList: []
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},

		onLoad: function(option) {
			this.getDictionary()
			if (!this.isObjectEmpty(option)) {
				const form = decodeURIComponent(option.formData)
				this.form = JSON.parse(form)
				console.log(this.form, 'option form')
				this.genderIndex = this.form.userSex - 1
				this.enrolStartDate = this.form.enrolStartDate
				this.enrolEndDate = this.form.enrolEndDate
				if (this.form.fileName && this.form.attachment) {
					this.fileList = [{
						name: this.form.fileName,
					}]
				}
				console.log(this.dicList, this.form.userEducation, this.stationEduIndex, 'this.stationEduIndex')
				// if (this.form.enrolTime) {
				//  this.enrolStartDate = this.form.enrolTime.split('~')[0]
				//  this.enrolEndDate = this.form.enrolTime.split('~')[1]
				// }

			} else {
				this.getResumeData()
			}
		},

		methods: {
			// 上传
			async uploadAvatar(e) {
				let {
					avatarUrl
				} = e.detail;
				const res = await this.$utils.uploadFile(avatarUrl)
				console.log(res, 'resss')
				if (res.code == 200) {
					this.form.userHead = res.fileName
				} else {
					this.form.userHead = ''
				}
			},
			async getDictionary() {
				const dictionaryData = await dictionary()
				this.dicList = dictionaryData.data.filter(item => item.field === 'stationEdu')[0].dicts
				if (this.form.userEducation) {
					this.stationEduIndex = this.findValByKey(this.dicList, this.form.userEducation)
				}
			},
			handleChangeGender(e) {
				this.genderIndex = e.detail.value
				this.form.userSex = Number(e.detail.value) + 1
			},
			handleChangeStationEduIndex(e) {
				console.log(e, 'handleChangeStationEduIndex')
				this.stationEduIndex = e.detail.value
				this.form.userEducation = this.dicList[e.detail.value]
			},
			handleChangeBirthDay(e) {
				this.form.birthTime = e.detail.value
			},
			handleChangeWorkDay(e) {
				this.form.workTime = e.detail.value
			},
			handleChangeEnrolStartDate(e) {
				this.enrolStartDate = e.detail.value
			},
			handleChangeEnrolEndDate(e) {
				this.enrolEndDate = e.detail.value
			},
			handleAddWorkExperience(index = '') {
				this.form.enrolStartDate = this.enrolStartDate
				this.form.enrolEndDate = this.enrolEndDate
				const formData = JSON.stringify(this.form)
				console.log(formData, 'formData')
				uni.navigateTo({
					url: `/subpage/talentemployment/employment/workexperience?formData=${encodeURIComponent(formData)}&index=${index}`
				})
			},
			handleChangeSalary(e) {
				this.form.hopeSalary = this.salaryList[e.detail.value]
			},
			// 从本地选择文件。
			chooseFile(e) {
				console.log(e, 'chooseFile')
				if (e.target.id !== 'uploadBox') {
					return
				}
				uni.chooseMessageFile({
					count: 1, //最多可以选择的文件数量，默认100
					//extension: ['.pdf'], //所选的文件的类型，默认全部
					success: (res) => {
						
						// 调用上传文件方法
						console.log(res, 'ressss')
						const file = res.tempFiles
						this.uploadFile(file)
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			async uploadFile(files) {
				console.log(files, 'files')
				const fileUrl = files[0].path
				const res = await this.$utils.uploadFile(fileUrl)
				if (res.code === 200) {
					this.fileList = files; //fileList需要在data中初始定义为一个数组
					this.form.attachment = res.fileName
					this.form.fileName = files[0].name
				} else {
					this.fileList = []
					this.form.attachment = ''
					this.form.fileName = ''
				}
			},
			// 删除
			delFile(index) {
				uni.showModal({
					title: '提示',
					content: '确定删除吗？',
					success: (res) => {
						if (res.confirm) {
							this.fileList = []
							this.form.attachment = ''
							this.form.fileName = ''
						}
					}
				});
			},
			// 保存简历
			async handleSubmit() {
				console.log(this.form, 'handleSubmit')
				if (this.enrolStartDate && this.enrolEndDate) {
					this.form.enrolTime = this.enrolStartDate + '~' + this.enrolEndDate
				}
				if (this.form.identityCard) {
					const validCard = this.isValidID(this.form.identityCard)
					if (!validCard) {
						uni.showToast({
							title: '身份证格式错误',
							icon: 'error'
						})
						return
					}
				}
				if (this.form.userPhone && !this.$utils.validatePhone(this.form.userPhone)) {
					uni.showToast({
						title: '手机格式错误',
						icon: 'error'
					})
					return
				}
				if (this.form.userEmail && !this.$utils.validateEmail(this.form.userEmail)) {
					uni.showToast({
						title: '邮箱格式错误',
						icon: 'error'
					})
					return
				}
				if (this.fileList.length) {
					this.form.fileName = this.fileList[0].name
				} else {
					this.form.fileName = ''
					this.form.attachment = ''
				}
				
				const requestApi = this.form.id ? updateResume : addResume
				const resultData = await requestApi(this.form)
				console.log(resultData, 'resultData')
				if (resultData.code === 200) {
					uni.showToast({
						title: '保存成功'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/subpage/talentemployment/employment/index'
						})
					}, 300)
				}
			},
			// 请求简历数据
			async getResumeData() {
				const resumeData = await getResume()
				if (resumeData.data) {
					this.form = resumeData.data
					this.genderIndex = resumeData.data.userSex - 1
					this.salaryIndex = this.findValByKey(this.salaryList, resumeData.data.hopeSalary)
					this.stationEduIndex = this.findValByKey(this.dicList, resumeData.data.userEducation)
					if (this.form.fileName && this.form.attachment) {
						this.fileList = [{
							name: this.form.fileName,
						}]
					}
					
					if (resumeData.data.enrolTime) {
						this.enrolStartDate = resumeData.data.enrolTime.split('~')[0]
						this.enrolEndDate = resumeData.data.enrolTime.split('~')[1]
					}
				}
				// this.form = resumeData.data
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			isObjectEmpty(obj) {
				return Object.keys(obj).length === 0;
			},
			findValByKey(arr, val) {
				return arr.findIndex(item => item === val)
			},
			// 身份证校验
			isValidID(id) {
				var pattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
				return pattern.test(id);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.resume-container {
		width: 100%;
		padding: 24rpx 32rpx 40rpx 32rpx;
		background: #F2F5FF;
		box-sizing: border-box;
	}

	.resume-form {
		width: 100%;
		padding: 18rpx 46rpx 36rpx;
		background: #FFFFFF;
		border-radius: 20px;
		box-sizing: border-box;

		.resume-form-item {
			display: flex;
			justify-content: space-between;
			padding: 32rpx 0;
			border-bottom: 2rpx solid rgba(52, 49, 79, 0.08);

			&.avatar {
				padding: 20rpx 0;
			}
			
			.file-box {
				display: flex;
				justify-content: flex-end;
			}

			&.introduct {
				display: block;
				position: relative;
				border-bottom: 0;
				padding: 32rpx 0 0;
			}

			.avatar-wrap {
				position: relative;
				display: block;
				width: 112rpx;
				height: 112rpx;
				margin: 0;
				padding: 0;
				border-radius: 50%;
				background: #ECEDF0;

				.avatar-box {
					width: 112rpx;
					height: 112rpx;
				}

				.default-avatar {
					position: absolute;
					width: 40rpx;
					height: 40rpx;
					left: 50%;
					bottom: 16rpx;
					transform: translateX(-50%);
				}

				&::after {
					border: 0;
				}
			}

			.label {
				display: block;
				font-weight: 400;
				font-size: 28rpx;
				color: #34314F;
				line-height: 20px;
			}

			.label-tip {
				font-weight: 400;
				font-size: 26rpx;
				color: rgba(52, 49, 79, 0.7);
				line-height: 18px;
				text-align: left;
			}

			.input-text {
				position: relative;
				text-align: right;
				font-size: 26rpx;

				&.select {
					padding-right: 40rpx;
				}

				&.select::after {
					position: absolute;
					top: 50%;
					right: 0;
					display: block;
					width: 32rpx;
					height: 32rpx;
					transform: translateY(-50%);
					background: url('@/static/images/index/right-arrow.png') no-repeat center;
					background-size: 100% 100%;
					content: '';
				}
			}

			.textarea-text {
				width: 100%;
				height: 440rpx;
				padding: 24rpx 0;
				box-sizing: border-box;
				font-size: 26rpx;
			}

			.count {
				position: absolute;
				bottom: 16rpx;
				right: 20rpx;
				font-size: 24rpx;
				color: rgba(52, 49, 79, 0.4);
			}

			.experience-head {
				display: flex;
				justify-content: space-between;

			}

			.experience-list {
				margin-top: 24rpx;

				.experience-item {
					margin-bottom: 28rpx;
					padding-bottom: 28rpx;
					border-bottom: 2rpx solid rgba(52, 49, 79, 0.08);

					&:last-child {
						margin-bottom: 0;
					}

					.company-name {
						display: block;
						margin-bottom: 14rpx;
						font-weight: 600;
						font-size: 26rpx;
						color: #34314F;
						line-height: 44rpx;
						text-align: left;
					}

					.job-name {
						font-weight: 600;
						font-size: 26rpx;
						color: #34314F;
						line-height: 44rpx;
						text-align: left;
					}

					.work-date {
						margin-left: 28rpx;
						font-weight: 400;
						font-size: 26rpx;
						color: rgba(52, 49, 79, 0.5);
						line-height: 32rpx;
						text-align: center;
						font-style: normal;
					}

					.work-desc {
						position: relative;
						display: block;
						margin-top: 20rpx;
						font-weight: 400;
						font-size: 26rpx;
						color: rgba(52, 49, 79, 0.7);
						line-height: 44rpx;
						text-align: left;
						font-style: normal;

						&::after {
							position: absolute;
							top: 50%;
							right: -36rpx;
							display: block;
							width: 32rpx;
							height: 32rpx;
							transform: translateY(-50%);
							background: url('@/static/images/index/right-arrow.png') no-repeat center;
							background-size: 100% 100%;
							content: '';
						}
					}
				}
			}

			.add-btn {
				width: 40rpx;
				height: 40rpx;
				background: url('@/static/images/more.png') no-repeat center;
				background-size: 100% 100%;
			}
		}
	}

	.submit-btn {
		margin-top: 44rpx;

		button {
			height: 48px;
			font-weight: 600;
			font-size: 32rpx;
			color: #34314F;
			line-height: 48px;
			text-align: center;
			font-style: normal;
			background: #FFDE6D;
			border-radius: 20px;

			&::after {
				border: 0;
			}
		}
	}
	.ellipsis {
		white-space: nowrap; /* 不换行 */
		overflow: hidden; /* 隐藏超出的内容 */
		text-overflow: ellipsis; /* 用省略号表示被隐藏的部分 */
		max-width: 300rpx; /* 设置最大宽度以限制文本的显示长度 */
	}
</style>